package com.eatrip.dao.implementation;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.eatrip.bean.Comune;
import com.eatrip.dao.ComuniDAO;

@Repository
@Transactional
public class ComuniDAOImple implements ComuniDAO {
	
	private HibernateTemplate hibernateTemplete;
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory){
		this.hibernateTemplete = new HibernateTemplate(sessionFactory);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Comune getComune(int idComune) {
		List<Comune> list = hibernateTemplete.find("FROM Comune WHERE id=?",idComune);
		if (list.size() == 0)
			return null;
		return list.get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Comune> getAllComuni(int start, int numRow) {
		Criteria criteria = hibernateTemplete.getSessionFactory().getCurrentSession().createCriteria(Comune.class);
			criteria.setFirstResult(start);
			criteria.setMaxResults(numRow);
		List<Comune> list = criteria.list();
		if (list.size() == 0)
			return null;
		return list;
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Comune> getComuniByCodiceProvincia(int codiceProvincia,
			int start, int numRow) {

		Criteria criteria = hibernateTemplete.getSessionFactory().getCurrentSession().createCriteria(Comune.class);
			criteria.add(Restrictions.eq("codiceProvincia",codiceProvincia));
			criteria.setFirstResult(start);
			criteria.setMaxResults(numRow);
		List<Comune> list = criteria.list();
		if (list.size() == 0)
			return null;
		return list;
	}

	@Override
	public void insertComune(Comune comune) {
		hibernateTemplete.save(comune);
	}

	@Override
	public void deleteComune(Comune comune) {
		hibernateTemplete.delete(comune);
	}

	@Override
	public void updateComune(Comune comune) {
		hibernateTemplete.update(comune);
	}

	@Override
	public void deleteAllComuni() {
		Query q = hibernateTemplete.getSessionFactory().getCurrentSession().createQuery("DELETE FROM Comune");
		int row  = q.executeUpdate();
		if (row==0)
			System.out.println("errore nella cancellazione comuni");
	}

}
